package org.timemachine.action.facadeBean;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.timemachine.action.facade.ChangeInfoFacade;
import org.timemachine.action.facade.EntityChangeFacade;
import org.timemachine.action.facade.ForwardChangeInfoFacade;
import org.timemachine.action.facade.ForwardEntityChangeFacade;
import org.timemachine.factory.ForwardChangeInfoFactory;
import org.timemachine.factory.spi.EntityChange;
import org.timemachine.model.base.ForwardChangeInfo;
import org.timemachine.model.base.ForwardEntity;

@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public class ForwardEntityChangeFacadeBean implements ForwardEntityChangeFacade {

	@PersistenceContext
	private EntityManager entityManager;

	@EJB
	private ForwardChangeInfoFacade forwardChangeInfoFacade;

	@EJB
	private ChangeInfoFacade changeInfoFacade;

	@EJB
	private EntityChangeFacade entityChangeFacade;

	@Override
	public void createForwardEntityChange(EntityChange entityChange) {

		ForwardChangeInfo beginChangeInfo = ForwardChangeInfoFactory
				.getNewInstance();
		forwardChangeInfoFacade.createChangeInfo(beginChangeInfo);

		entityChange.setBeginChangeInfo(beginChangeInfo);
		entityChange.setEndChangeInfo(changeInfoFacade.findInfiniteInstance());
		ForwardEntity forwardEntity = new ForwardEntity();
		forwardEntity.setForwardChangeInfo(beginChangeInfo);
		forwardEntity.setEntityName(entityChange.getClass().getName());

		entityManager.persist(forwardEntity);
		entityManager.persist(entityChange);

	}

	@Override
	public EntityChange updateForwardEntityChange(EntityChange entityChange) {

		EntityChange previousEntityChange = (EntityChange) entityChangeFacade
				.findPreviousEntityChange(entityChange);

		createForwardEntityChange(entityChange);

		previousEntityChange
				.setEndChangeInfo(entityChange.getBeginChangeInfo());

		return entityManager.merge(previousEntityChange);
	}

	@Override
	public EntityChange removeForwardEntityChange(EntityChange entityChange) {

		EntityChange previousEntityChange = (EntityChange) entityChangeFacade
				.findPreviousEntityChange(entityChange);

		createForwardEntityChange(entityChange);

		previousEntityChange
				.setEndChangeInfo(entityChange.getBeginChangeInfo());

		return entityManager.merge(previousEntityChange);
	}

}
